﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ProgramTest
{
    public class TaskShow
    {
        public static void Show()
        {
            //Class1 class1 = new Class1();
            //int i = class1.ID;
            //没有什么是包一层无法解决的，如果有，那就再包一层

            //1、Task实现限制线程数量 2、Parallel 控制并发线程数量
            {
                List<int> list = new List<int>();
                for (int i = 0; i < 10000; i++)
                {
                    list.Add(i);
                }
                Action<int> action = i =>
                {
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
                    Thread.Sleep(new Random(i).Next(100, 300));
                };
                List<Task> tasksList = new List<Task>();
                foreach (var i in list)
                {
                    int k = i;
                    Task task = Task.Run(() => action.Invoke(k));
                    tasksList.Add(task);
                    if (tasksList.Count > 10)
                    {
                        Task.WaitAny(tasksList.ToArray());
                        tasksList.Remove(tasksList.Find(x => x.Status == TaskStatus.RanToCompletion));
                    }
                }
                Task.WhenAll(tasksList.ToArray());
            }
            //获取Task多线程哪个线程先结束:1、TaskFactory 2、Task一个子类
            {
                TaskFactory taskFactory = new TaskFactory();

            }
            //Thread.Sleep 休眠，会卡界面，阻塞线程
            //Task.Delay  延迟，不会卡界面
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                Task.Delay(2000).ContinueWith(x =>
                {
                    stopwatch.Stop();
                    Console.WriteLine(stopwatch.ElapsedMilliseconds);
                });
            }
            //Parallel 并行线程 在Task的基础上做了封装 4.5
            //卡界面，Parallel线程参与计算，节约了一个线程
            {

            }


        }
    }
}
